<?php
namespace wlcat\http\view;
use wlcat\src\Register;

class View
{
    protected $variables = array();
    protected $_controller;
    protected $_action;
    protected $smarty;

    function __construct($controller, $action)
    {
        $this->_controller = $controller;
        $this->_action = $action;
        $this->smarty  = Register::get(Register::SMARTY_CLASS);
        $this->smarty->addTemplateDir(FRAME_PATH."http/view");
        $this->smarty->addTemplateDir(C('smarty.templateDir'));
        $this->smarty->setCompileDir(C('smarty.compileDir'));
        $this->smarty->setCacheDir(C('smarty.cacheDir'));
        $this->smarty->setCache(C('smarty.cache'));
        $this->smarty->setCacheTime(C('smarty.cache_lifetime'));
        $this->smarty->setDebug(C('debugging'));
        $this->initSmartyAssign(C('smarty.assignVar'));
    }
    /** 分配变量 **/
    function assign($name, $value)
    {
        $this->smarty->assign($name, $value);
    }
    /** 渲染显示 **/
    function display($file = '')
    {
        $path       = empty($file)
                        ?  strtolower($this->_controller) . '/' . strtolower($this->_action) . '.php'
                        :  $file;
        $this->smarty->display($path);
    }

    /*初始化smarty的变量*/
    function initSmartyAssign($assigns)
    {
        $pattern = "/(.+)?\{(.+?)\}(.+)?/";
        foreach ($assigns as $key => &$value)
        {
            if (preg_match($pattern, $value))
            {
                preg_match_all($pattern, $value, $match);
                if (
                    array_key_exists(2, $match)
                    && array_key_exists(0, $match[2])
                ) {
                    $matchKey = trim($match[2][0]);
                    $assigns[$key] = str_replace('{'.$matchKey.'}', $assigns[$matchKey], $value);
                }

            }
        }
        foreach ($assigns as $key => $value)
        {
            $this->assign($key, $value);
        }
    }

}